﻿using System;
using System.Linq;
using CRM.Database.Model;

namespace CRM.Syncroniser
{
   public  class AddressesSyncroniser:ISyncronise
    {
       #region Implementation of ISyncronise

       /// <summary>
       /// Запуск синхронизации
       /// </summary>
       /// <returns>Результат запуска</returns>
       public bool Syncronise()
       {
           var col = new LegalEntitiesCollection();
           
           
           foreach(var le in col.LegalEntitiesList)
           {
               if(le.Addresses.Count>1)
               {
                   if(le.Addresses.ToList().Where(c=>c.IsPrimary != null && (bool) c.IsPrimary).Count()>1)
                   {
                       foreach(var addr in le.Addresses)
                       {
                           addr.IsPrimary = false;
                       }

                       var addrPrimary = le.Addresses.First();
                       addrPrimary.IsPrimary = true;

                       col.Save();
                   }


                   if (le.Addresses.ToList().Where(c => c.IsPrimary != null && (bool)c.IsPrimary).Count() == 0)
                   {
                       foreach (var addr in le.Addresses)
                       {
                           addr.IsPrimary = false;
                       }

                       var addrPrimary = le.Addresses.First();
                       if (addrPrimary != null) addrPrimary.IsPrimary = true;

                       col.Save();
                   }
               }
               if (le.Addresses.Count > 0)
               {
                   if (le.Addresses.ToList().Where(c => c.IsPrimary != null && (bool) c.IsPrimary).Count() == 0)
                   {
                       foreach (var addr in le.Addresses)
                       {
                           addr.IsPrimary = false;
                       }

                       var addrPrimary = le.Addresses.First();
                       addrPrimary.IsPrimary = true;

                       col.Save();
                   }
               }
           }


          
           
           return true;
       }

       #endregion
    }
}
